package com.wbao.dianniu.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.text.emoji.EmojiCompat;
import android.support.text.emoji.bundled.BundledEmojiCompatConfig;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.igexin.sdk.PushManager;
import com.meizu.cloud.pushsdk.util.MzSystemUtils;
import com.mob.MobSDK;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.qcloud.timchat.utils.InitBusiness;
import com.tencent.qcloud.timchat.utils.LoginBusiness;
import com.tencent.qcloud.timchat.utils.MessageEvent;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.DnApplication;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.service.DemoIntentService;
import com.wbao.dianniu.service.GTPushService;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;


public class SplashActivity extends Activity implements ILoginListener, /*View.OnClickListener,*/ TIMCallBack {
    private ImageView imageView;
    private LoginManager manager;
    boolean isFirstIn = false;
    protected static final String TAG = SplashActivity.class.getSimpleName();
    private String type = null;
    private String id = null;
    private Class userPushService = GTPushService.class;
    private static final int REQUEST_PERMISSION = 0;
    private String url = "http://dianniu.image.alimmdn.com/advert/index.jpg?t=";
    private Button skipBtn;
    private Boolean isAdLoaded = false;
    private Handler handler;
    private boolean autoStatus = false;
    private final int LOGIN_STATUS_INIT = 0x01;
    private final int LOGIN_STATUS_FAIL = 0x02;
    private final int LOGIN_STATUS_SUCESS = 0x03;
    private int loginStatus = LOGIN_STATUS_INIT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setContentView(R.layout.activity_splash);

        initView();
        // 定时器
        handler = new Handler();
        /*

        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.READ_PHONE_STATE);
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionsList.size() == 0) {
                init();
            } else {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_PERMISSION);
            }
        } else {
            init();
        }
        */
        AsyncInitTask();
    }

    private void init() {
        initApplication();
        initManager();
        initIM();

        boolean net = Utils.isNetworkAvaiable(SplashActivity.this);
        if (!net) {
            Notification.showToastMsg(SplashActivity.this, "网络不可用，请检测网络");
            // TODO Auto-generated method stub
            intoLoginActivity();
            return;
        }

        if (getAutoStatus()) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    autoLogin();
                }
            });
        } else {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    intoLoginActivity();
                }
            }, 1 * 1000);
        }

        /*SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        int loglvl = pref.getInt("loglvl", TIMLogLevel.DEBUG.ordinal());
        //初始化IMSDK
        InitBusiness.start(getApplicationContext(), loglvl);
        //初始化TLS
        TlsBusiness.init(getApplicationContext());
        String id = TLSService.getInstance().getLastUserIdentifier();
        UserInfo.getInstance().setId(id);
        UserInfo.getInstance().setUserSig(TLSService.getInstance().getUserSig(id));
        presenter = new SplashPresenter(this);
        presenter.start();*/
    }

    private void initView() {
        imageView = findViewById(R.id.splash_imageview);
        skipBtn = findViewById(R.id.skip_advert_btn);
        skipBtn.setOnClickListener(listener);
    }


    private void initIM() {
        //初始化IMSDK
        InitBusiness.start(getApplicationContext(), TIMLogLevel.DEBUG.ordinal());
        // 初始化用户配置
        InitBusiness.userConfig();
    }


    private void initManager() {
        //获取用户名和密码 自动登录
        manager = new LoginManager(this);
        manager.addLoginListener(this);
    }

    private boolean getAutoStatus() {
        autoStatus = SharedPreferencesUtils.getAutoLoginStatus(this);
        String username = SharedPreferencesUtils.getUserName(this);
        String password = SharedPreferencesUtils.getPassword(this);
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            SharedPreferencesUtils.setAutoLoginStatus(this, false);
            autoStatus = false;
        }
        return autoStatus;
    }

    private void scheduleIntent() {
        // 判断是否是从网页跳转的，如果是从网页跳转的，直接跳转到对应界面
        Intent intent = getIntent();
        String scheme = intent.getScheme();
        if (null != scheme) {
            if (scheme.equals("dianniu")) {
                Uri uri = intent.getData();
                if (uri != null) {
                    String host = uri.getHost();
                    String dataString = intent.getDataString();
                    //获得参数值
                    type = Utils.getQueryParam(dataString, "shareType");
                    id = Utils.getQueryParam(dataString, "id");
                    // 解析type
                }
            }
        }
    }


    private void autoLogin() {
        //------------这个为兼容性测试所用-------------------
//        auto_status = true;
//        username = "13900000006";
//        password = Utils.Md5("123456");
        //------------------------------------------------
        String username = SharedPreferencesUtils.getUserName(this);
        String password = SharedPreferencesUtils.getPassword(this);
        /**  这里做兼容性 -- 1.2版本的用户保存的是明文的密码，自动更新后，自动登录会提示用户名密码错，需要先加密再请求登录  */
        if (password.length() != 32) {// 把32位密码默认为已经加密的密码
            password = Utils.Md5(password);
        }
        String pushClientId = SharedPreferencesUtils.getClientId(this);
        manager.Login(this, username, password, Utils.getDeviceId(this), null, null, Utils.getVersionName(this), null, pushClientId);
    }


    private void initApplication() {
        EmojiCompat.Config config = new BundledEmojiCompatConfig(getApplicationContext());
        EmojiCompat.init(config);
        // 初始化分享组件，小内存消耗，可以多次初始化
        MobSDK.init(getApplicationContext(), "1475bc40e11d8", "0400de1ade4700e112b21b92e24b9c40");
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.enableEncrypt(true);
        MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);
        initImageLoader();

        /*getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
            }
        });*/

        //sharedPreferences初始化
        SharedPreferencesUtils.init(this);
    }

    Runnable timeoutRunable = new Runnable() {
        @Override
        public void run() {
            if (!isAdLoaded) {
//                Log.e(TAG,"timeoutRunable ...");
                Glide.with(SplashActivity.this).pauseRequests();
                if (loginStatus == LOGIN_STATUS_SUCESS) {
                    intoMainActivity();
                } else {
                    intoLoginActivity();
                }
            }
        }
    };

    // 广告自动取消定时任务
    Runnable adTimeoutRunable = new Runnable() {
        @Override
        public void run() {
//            Log.e(TAG,"adTimeoutRunable ...");
            if (loginStatus == LOGIN_STATUS_SUCESS) {
                intoMainActivity();
            } else {
                intoLoginActivity();
            }
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void loadAdImage() {
//        if (!this.isDestroyed()) {
        long t = System.currentTimeMillis();
        url = url + t;
        Glide.with(DnApplication.getContext()).load(url)
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//                            Log.e(TAG,"onResourceReady ...");
                        isAdLoaded = true;
                        handler.removeCallbacks(timeoutRunable);
                        imageView.setImageDrawable(resource);
                        skipBtn.setVisibility(View.VISIBLE);
                        handler.postDelayed(adTimeoutRunable, 2 * 1000);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
//                            Log.e(TAG,"onLoadFailed ...");
                        handler.removeCallbacks(timeoutRunable);
                        isAdLoaded = true;
                        if (loginStatus == LOGIN_STATUS_SUCESS) {
                            intoMainActivity();
                        } else {
                            intoLoginActivity();
                        }
                    }
                });
//        }

    }


    private void initImageLoader() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).imageDownloader(
                new BaseImageDownloader(this, 60 * 1000, 60 * 1000)) // connectTimeout超时时间
                .build();
        ImageLoader.getInstance().init(config);
    }

    private void initGTPush() {
        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }

        PushManager.getInstance().initialize(this.getApplicationContext(), GTPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeLoginListener(this);
        }
        if (null != handler) {
            handler.removeCallbacks(timeoutRunable);
            handler.removeCallbacks(adTimeoutRunable);
        }
    }

    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        loginStatus = LOGIN_STATUS_FAIL;
        // 过三秒 如果广告图片未加载成功，则不再加载图片直接向下执行
        handler.postDelayed(timeoutRunable, 3 * 1000);
        // 显示广告页
        loadAdImage();
    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        loginStatus = LOGIN_STATUS_SUCESS;
        // TODO Auto-generated method stub
        Utils.saveLoginData(this, objdata);
//        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getTencentImUserSig());
//        handler.postDelayed(timeoutRunable, 3 * 1000);
        LoginBusiness.loginIm(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getTencentImUserSig(), this);

    }

    private void intoLoginActivity() {
        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
        SplashActivity.this.finish();
    }

    private void intoMainActivity() {
//        Log.e(TAG,"intoMainActivity。。。");
        scheduleIntent();
        // 成功 界面跳转
        Intent intent = new Intent();
        if (null != type && null != id) {
            intent.putExtra(Const.INTENT_SCHEME_TYPE, type);
            intent.putExtra(Const.INTENT_SCHEME_ID, id);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setClass(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        SplashActivity.this.finish();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
                    init();
                } else {
                    Notification.toast(this, "您需要开启权限,并重启应用");
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        /*if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            } else {
                Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }*/
    }

    /*@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.skip_advert_btn:

                handler.removeCallbacks(adTimeoutRunable);
                if (loginStatus == LOGIN_STATUS_SUCESS) {
                    intoMainActivity();
                } else {
                    intoLoginActivity();
                }
                break;
            default:
                break;
        }
    }*/


    // IMSDK登录成功后回调， 注册推送服务
    private void registerPushService() {
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        String deviceMan = android.os.Build.MANUFACTURER;
        //注册小米和华为推送
        if (deviceMan.equals("Xiaomi") && shouldMiInit()) {
            MiPushClient.registerPush(getApplicationContext(), "2882303761517845834", "5741784565834");
        } else if (deviceMan.equals("HUAWEI")) {
//            com.huawei.android.pushagent.PushManager.requestToken(this);
        }


        //魅族推送只适用于Flyme系统,因此可以先行判断是否为魅族机型，再进行订阅，避免在其他机型上出现兼容性问题
        if (MzSystemUtils.isBrandMeizu(getApplicationContext())) {
            com.meizu.cloud.pushsdk.PushManager.register(this, "1001418", "13b58f7f778a4d9ba54b22fc42b186fc");
        }

    }

    /**
     * 判断小米推送是否已经初始化
     */
    private boolean shouldMiInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onError(int i, String s) {
        switch (i) {
            case 6208:
                //离线状态下被其他终端踢下线
                // 再次掉登录接口
                GlobalUserData userData = new GlobalUserData();
                LoginBusiness.loginIm(userData.getEnvironemt() + GlobalContext.getAccountId(), userData.getUserSig(), SplashActivity.this);
                break;
            case 6200:
                Notification.toast(SplashActivity.this, getString(R.string.login_error_timeout));
                intoLoginActivity();
                break;
            default:
                Notification.toast(SplashActivity.this, s);
                intoLoginActivity();
                break;
        }

    }

    @Override
    public void onSuccess() {
        // 广告加载定时器  过三秒 如果广告图片未加载成功，则不再加载图片直接向下执行
        handler.postDelayed(timeoutRunable, 3 * 1000);
        // 加载广告
        loadAdImage();
        registerPushService();
    }


    private void AsyncInitTask() {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                final List<String> permissionsList = new ArrayList<>();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED))
                        permissionsList.add(Manifest.permission.READ_PHONE_STATE);
                    if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                        permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (permissionsList.size() == 0) {
                        init();
                    } else {
                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                REQUEST_PERMISSION);
                    }
                } else {
                    init();
                }
                return null;
            }
        }.execute();
    }


    NoDoubleClickListener listener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.skip_advert_btn:
                    handler.removeCallbacks(adTimeoutRunable);
                    if (loginStatus == LOGIN_STATUS_SUCESS) {
                        intoMainActivity();
                    } else {
                        intoLoginActivity();
                    }
                    break;
                default:
                    break;
            }
        }
    };

}

